package besta.moon.command;

import java.io.*;

import besta.moon.MoonException;
import besta.moon.MoonConnection;
import besta.moon.statement.MoonStatement;
import besta.moon.MoonCode;
import besta.moon.MoonLogger;
import besta.moon.MoonCommand;
import besta.moon.sql.parser.SQLTokenizer;
import besta.moon.util.MoonUtils;

public class CommandCreateDatabase extends MoonCommand {

    public CommandCreateDatabase(MoonLogger log, String name) {
        super(log);
        this.type = SQLTokenizer.DATABASE;
        if (name.startsWith("file:")) {
            name = name.substring(5);
        }
        this.name = name;
    }

    @Override
    public void executeImpl(MoonConnection con, MoonStatement st) throws Exception {
        if (con.isReadOnly()) {
            throw MoonException.create(MoonCode.DB_READONLY);
        }
        File dir = new File(name);
        dir.mkdirs();
        if (!new File(dir, MoonUtils.MASTER_FILENAME).createNewFile()) {
            throw MoonException.create(MoonCode.DB_EXISTENT, name);
        }
    }

}
